<template>
  <div class="boxPicker">
    <div class="IroBox">
      <canvas ref="colorCanvas" width="260" height="260" @click="selectColor"></canvas>
    </div>
    <div class="IroSlider">
      <ColorSlider v-model="color" @change="drawColorCanvas" />
    </div>
    <el-button type="primary" class="wAuto" @click="generateRandomColor">生成随机颜色</el-button>
  </div>
</template>
<script setup lang="ts">
import ColorSlider from './ColorSlider.vue';
import { rgbToHex } from '@/utils/color';
const props = withDefaults(
  defineProps<{
    modelValue?: string; //颜色
  }>(),
  {
  },
);

// 定义 emits
const emit = defineEmits(['update:modelValue', 'change']);
// 更新 modelValue 的方法
const updateValue = (newValue: string) => {
  emit('update:modelValue', newValue);
  emit('change', newValue);
};
const setcolor = (hex: string) => {

}
//生成随机颜色
const generateRandomColor = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  const hex = rgbToHex({ r, g, b });
  updateValue(hex)
}
interface RGB {
  r: number;
  g: number;
  b: number;
}

const color = ref('#FF0000')
const colorCanvas = ref(null)
const drawColorCanvas = () => {
  const canvas: any = colorCanvas.value
  const ctx = canvas.getContext('2d');
  // 第二个渐变: 水平方向，从rgb(255, 255, 255)到#2485EA
  var gradientH = ctx.createLinearGradient(0, 0, canvas.width, 0);
  gradientH.addColorStop(0, 'rgba(255, 255, 255, 1)'); // 设置一定的透明度
  gradientH.addColorStop(1, color.value);
  ctx.fillStyle = gradientH;
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 第一个渐变: 垂直方向，从rgba(0, 0, 0, 0)到rgb(0, 0, 0)
  var gradientV = ctx.createLinearGradient(0, 0, 0, canvas.height);
  gradientV.addColorStop(0, 'rgba(0, 0, 0, 0)');
  gradientV.addColorStop(1, 'rgba(0, 0, 0, 1)'); // 注意这里设置了半透明
  ctx.fillStyle = gradientV;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}
const selectColor = (event: any) => {
  const canvas: any = colorCanvas.value
  const ctx = canvas.getContext('2d');
  if (!ctx) return;
  // 获取点击位置相对于 canvas 的坐标
  const rect = canvas.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  const pixelData = ctx.getImageData(x, y, 1, 1).data;
  const [r, g, b] = pixelData;
  const rgb = { r, g, b }
  const hex = rgbToHex(rgb)
  updateValue(hex)
}
onMounted(() => {
  drawColorCanvas()
});

onBeforeUnmount(() => { });
</script>
<style scoped lang="scss">
.boxPicker {
  --w: 260px;
  width: var(--w);

  .IroBox {
    width: var(--w);
    height: var(--w);
    border-radius: 16px;
    overflow: hidden;
    position: relative;
  }

  .IroSlider {
    position: relative;
    width: var(--w);
    border-radius: 100px;
    overflow: hidden;
    display: flex;
  }

  >* {
    &:not(:last-child) {
      margin-bottom: 12px;
    }
  }
}
</style>